<?php

class ControllerAccountSocial extends Controller
{

    public function weixin_auth()
    {
        // https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&lang=zh_CN
        $source_url = $this->request->get['source_url'];
        $redirect_uri = HTTP_SERVER . "index.php?route=account/social/weixin_auth_callback&source_url=" . $source_url;
        $weixin_auth_2url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . "appid=" . WX_AppID . "&redirect_uri=" . urlencode($redirect_uri) . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        $this->response->redirect($weixin_auth_2url);
    }

    // 获取记录用户微信信息,生成系统账号
    public function weixin_auth_callback()
    {
        $source_url = $this->request->get['source_url'];

        $code = $this->request->get['code'];

        $token = $this->Wx_OAuth2API_GetAccessToken($code, WX_AppID, WX_AppSecret);

        $refreshAccess_token = $this->Wx_OAuth2API_RefreshAccess_token($token->refresh_token, WX_AppID);

        $openid = $refreshAccess_token->openid;

        $this->session->data['wx_openid'] = $openid;

        if (isset($openid)) {
            $this->load->model('account/activity');
            $this->load->model('account/customer');
            $this->load->model('account/social');
            $userinfo = $this->Wx_OAuth2API_GetUserInfo($refreshAccess_token->access_token, $openid);


            $customer_info = $this->model_account_customer->getCustomerByOpenId($openid);

            $customer = array(
                 'image' =>$userinfo->headimgurl,
                 'open_id' =>$openid,
                 'name' =>$userinfo->nickname
            );
            if($customer_info){
                if ($this->customer->loginById($customer_info['customer_id'])) {
                    $this->model_account_customer->updateCustomerByWx($this->customer->getId(),array(
                        'firstname' => $userinfo->nickname,
                        'image' => $userinfo->headimgurl,
                        'open_id' => $openid
                      )
                    );
                    $this->model_account_social->updateSocial(array(
                          'uid'=>$openid,
                          'customer_id'=>$customer_info['customer_id'],
                          'social_type'=>1
                    ));
                    $activity_data = array(
                        'customer_id' => $this->customer->getId(),
                        'name' => $this->customer->getFirstName()
                    );
                    $this->model_account_activity->addActivity('login', $activity_data);
                    $this->response->redirect(HTTP_WX_WEB ."#/". $source_url);
                } else {
                    $this->response->redirect(Http_404);
                }
            }else{
               $this->response->redirect(Http_Register . "?source_url=". $source_url."&userinfo=" .json_encode($customer));
            }

        } else {
            $this->response->redirect(Http_404);
        }
    }


    /* public function weixin_auth_callback()
    {
        $source_url = $this->request->get['source_url'];

        $code = $this->request->get['code'];

        $token = $this->Wx_OAuth2API_GetAccessToken($code, WX_AppID, WX_AppSecret);

        $refreshAccess_token = $this->Wx_OAuth2API_RefreshAccess_token($token->refresh_token, WX_AppID);

        $openid = $refreshAccess_token->openid;

        $this->session->data['wx_openid'] = $openid;

        if (isset($openid)) {
            $this->load->model('account/activity');
            $this->load->model('account/customer');
            $this->load->model('account/social');
            $userinfo = $this->Wx_OAuth2API_GetUserInfo($refreshAccess_token->access_token, $openid);
            $customer_info = $this->model_account_customer->getCustomerByOpenId($openid);
            $customer = array(
                'wx_image' => $userinfo->headimgurl,
                'open_id' => $openid,
                'name' => $userinfo->nickname
            );
            if (! $customer_info) {
                $customer_id = $this->model_account_customer->autoAddCustomer(array(
                    'firstname' => $userinfo->nickname,
                    'wx_image' => $userinfo->headimgurl,
                    'open_id' => $openid
                ));
                if ($customer_id > 0) {
                    $this->model_account_social->addSocial(array(
                        'uid' => $openid,
                        'social_type' => 1,
                        'customer_id' => $customer_id
                    ));
                    $this->response->redirect(HTTP_WX_WEB . "?customer_id=" . $customer_id . "#login");
                }
            } else {
                $this->model_account_customer->updateCustomerByWx($customer_info['customer_id'], array(
                    'firstname' => $userinfo->nickname,
                    'wx_image' => $userinfo->headimgurl,
                    'open_id' => $openid
                ));
                if (! empty($customer_info['yx_customer_id']) && strlen($customer_info['yx_customer_id']) > 0) {
                    //更新优学派用户信息
                    $yx_customer = $this->getyxuserinfo($customer_info['customer_id']);
                    if($yx_customer){
                        $this->model_account_customer->updateCustomerByYx(array(
                              'telephone'=>$yx_customer['telephone'],
                               'firstname'=>$yx_customer['name'],
                               'email'=>$yx_customer['email']

                        ),$customer_info['customer_id']);
                        if($yx_customer->machines){
                            $machines = $yx_customer->machines;
                            $this->model_account_customer->deleteCustomerHardWare($customer_info['customer_id']);
                            foreach ($machines as $machine){
                                //$this->model_account_customer->addCustomerHardWare();
                            }
                        }
                        if($yx_customer->children){
                            $children=$yx_customer->children;
                            $this->model_account_customer->deleteCustomerChild($customer_info['customer_id']);
                            foreach ($children as $child){
                                // $this->model_account_customer->addCustomerChild();
                            }
                        }
                        if(!$this->model_account_customer->getCustomerChild()){
                            $source_url = "/bindchild";
                        }

                    }
                    $this->customer->loginById($customer_info['customer_id']);

                    $this->response->redirect(HTTP_WX_WEB . "?customer_id=" . $customer_id . "#$source_url");
                } else {
                    $this->response->redirect(HTTP_WX_WEB . "?customer_id=" . $customer_id . "#login");
                }
            }
        }
    } */

    public function getyxuserinfo($customer_id){

        $url = $this->baseurl . 'user/info';
        $rand = time();

        $user_flag = $customer_id;
        $sign = md5("GET".$url."client_key=$this->client_key"."rand=$rand"."user_flag=$user_flag".$this->secret_key);
        $url = $url . "?sign=$sign&client_key=$this->client_key&rand=$rand&user_flag=$user_flag";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res);
        if($result->msgCode==302){
            return $result->data;

        }else {

            return null;
        }

    }



    /**
     * 对应微信API的 "用户管理"=> "网页授权获取用户基本信息 第二步：通过code换取网页授权access_token”
     *
     * @return result
     */
    protected function Wx_OAuth2API_GetAccessToken($code, $appId, $appSecret)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res);

        return $result;
    }

    /**
     * 对应微信API的 "用户管理"=> "网页授权获取用户基本信息 第三步：刷新access_token（如果需要）”
     *
     * @link
     *
     * @return result
     */
    protected function Wx_OAuth2API_RefreshAccess_token($refreshToken, $appId)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appId&grant_type=refresh_token&refresh_token=$refreshToken";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res);
        return $result;
    }

    /**
     * 对应微信API的 "用户管理"=> "网页授权获取用户基本信息 第四步：拉取用户信息(需scope为 snsapi_userinfo)”
     *
     * @link
     *
     * @return void
     */
    protected function Wx_OAuth2API_GetUserInfo($accessToekn, $openId, $lang = "zh_CN")
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToekn&openid=$openId&lang=$lang";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res);
        return $result;
    }
}